#include "messagepackage.h"

MessagePackage::MessagePackage()
{

}

QString MessagePackage::type()
{
    return obj["type"].toString();
}

void MessagePackage::setType(QString type)
{
    obj.insert("type",type);
}

void MessagePackage::setGroupId(const QString &id)
{
    obj.insert("group_id",id);
}

QString MessagePackage::groupId()
{
    return obj["group_id"].toString();
}

void MessagePackage::setGroupName(const QString &name)
{
    obj.insert("group_name",name);
}

QString MessagePackage::groupName()
{
    return obj["group_name"].toString();
}

void MessagePackage::setMemberList(const QStringList &members)
{
    QJsonArray memberArray;
    for (const QString &member : members)
    {
        memberArray.append(member);
    }
    obj.insert("members", memberArray);  // 使用合适的字段名
}


QStringList MessagePackage::memberList()
{
    QStringList members;
    if (obj.contains("members"))
    {
        QJsonArray array = obj["members"].toArray();
        for (const QJsonValue &value : array)
        {
            members.append(value.toString());
        }
    }
    return members;
}

QString MessagePackage::userName()
{
    return obj["userName"].toString();
}

void MessagePackage::setUserName(QString name)
{
    obj.insert("userName",name);
}

QString MessagePackage::recvName()
{
    return obj["RecvName"].toString();
}

void MessagePackage::setRecvName(QString name)
{
    obj.insert("RecvName",name);
}

QString MessagePackage::getMessage()
{
    return obj["Message"].toString();
}

void MessagePackage::setMessage(QString mess)
{
    obj.insert("Message",mess);
}

QString MessagePackage::userPswd()
{
    return obj["userPswd"].toString();
}

void MessagePackage::setUserPswd(QString pswd)
{
    obj.insert("userPswd",pswd);
}

bool MessagePackage::result()
{
    return obj["result"].toBool();
}

void MessagePackage::setResult(bool res)
{
    obj.insert("result",res);
}

QByteArray MessagePackage::getData()
{
    QJsonDocument doc(obj);
    return doc.toJson(QJsonDocument::Compact);
}

void MessagePackage::recvMessage(MessagePackage &pack, QTcpSocket *socket)
{
    int len = 0;
    socket->read((char*)&len,sizeof(int));
    QByteArray bytes;
    bytes=socket->read(len);
    pack.obj = QJsonDocument::fromJson(bytes).object();
}

void MessagePackage::sendMessage(MessagePackage &pack, QTcpSocket *socket)
{
    QByteArray bytes = pack.getData();
    int len = bytes.size();
    socket->write((char*)&len,sizeof(int));
    socket->write(bytes,len);
}
void MessagePackage::setInviteUser(const QString &username) {
    obj.insert("invite_user", username);
}

QString MessagePackage::inviteUser() {
    return obj["invite_user"].toString();
}
